package com.tt;

import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;

import com.google.gson.Gson;
import com.stkouyu.entity.LgEvaluateObj;
import com.tt.listener.OnInitEngineListener;
import com.tt.listener.OnRecordListener;
import com.tt.setting.EngineSetting;

import org.json.JSONException;
import org.json.JSONObject;

/**
 * Created by pengmi on 2018/7/31.
 * Description:对SkEgnManager 进行二次封装
 */


public class LancooSkEgnManager {

    public static LancooSkEgnManager lancooSkEgnManager;
    private boolean isShowScore,isEnableScore;
    private OnLancooRecordListener onLancooRecordListener;
    private Context mContext;
    private final int MST_OUTTIME=100;


    private LancooSkEgnManager(Context mContext){
        this.mContext=mContext;
    }

    public static LancooSkEgnManager getInstance(Context mContext){
        if(lancooSkEgnManager==null){
            lancooSkEgnManager=new LancooSkEgnManager(mContext);
        }
        return lancooSkEgnManager;
    }

    //自定义url
    public void startRecord(String content,String url,OnLancooRecordListener onLancooRecordListener){
        this.onLancooRecordListener=onLancooRecordListener;
        isEnableScore=true;
        isShowScore=true;
        mHandler.removeMessages(MST_OUTTIME);
        SkEgnManager.getInstance(mContext).startRecord(CoreType.EN_SENT_EVAL, content, QType.QTYPE_EMPTY,mOnRecordListener);
//        SkEgnManager.getInstance(mContext).startRecord(CoreType.EN_SENT_EVAL, content,QType.QTYPE_EMPTY,url,mOnRecordListener);
//        SkEgnManager.getInstance(mContext).startRecord(RequestConstants.CORETYPE,  content, RequestConstants.QTYPE, mHandler);
    }


    public void startRecord(String content,OnLancooRecordListener onLancooRecordListener){
        this.onLancooRecordListener=onLancooRecordListener;
        isEnableScore=true;
        isShowScore=true;
        SkEgnManager.getInstance(mContext).startRecord(CoreType.EN_SENT_EVAL, content, QType.QTYPE_EMPTY, mOnRecordListener);
//        SkEgnManager.getInstance(mContext).startRecord(RequestConstants.CORETYPE, content, RequestConstants.QTYPE, mHandler);
    }

    public void stopRecord(boolean isShowScore){
        this.isShowScore=isShowScore;
        if(!isShowScore){
            SkEgnManager.getInstance(mContext).stopRecord();
            SkEgnManager.getInstance(mContext).cancelRecord();
            mHandler.removeMessages(MST_OUTTIME);
        }else{
            SkEgnManager.getInstance(mContext).stopRecord();
            mHandler.sendEmptyMessageDelayed(MST_OUTTIME,15000);
        }
    }


    OnRecordListener mOnRecordListener = new OnRecordListener() {
        @Override
        public void onRecordStart() {
            //开始录制
            if(onLancooRecordListener!=null){
                onLancooRecordListener.onRecordStart();
            }
        }

        @Override
        public void onRecording(int vad_status, int sound_intensity) {
            //录制中
            if(onLancooRecordListener!=null){
                onLancooRecordListener.onRecording(vad_status,sound_intensity);
            }
        }
        @Override
        public void onRecordEnd(String result) {
            mHandler.removeMessages(MST_OUTTIME);
//            Log.e("aaaa","onRecordEnd:"+result+","+isShowScore+","+isEnableScore);
            if(isEnableScore){
                isEnableScore=false;
                try{
                    if(isShowScore){
                        final JSONObject json = new JSONObject(result);
                        int grade = json.getJSONObject("result").getInt("overall");
                        String path = SkEgnManager.getInstance(mContext).getPath();
                        Gson gson=new Gson();
                        LgEvaluateObj skegnResult = gson.fromJson(result, LgEvaluateObj.class);
                        if(onLancooRecordListener!=null&&!TextUtils.isEmpty(path)){
                            onLancooRecordListener.onRecordEnd(grade,path,skegnResult);
                        }else{
                            onLancooRecordListener.onRecordError("path is empty!");
                        }
                    }

                } catch (JSONException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                    if(onLancooRecordListener!=null&&isShowScore){
                        onLancooRecordListener.onRecordError(e.toString());
                    }
                }
            }
        }
    };

//    private OnSkEgnInitListener onSkEgnInitListener;
    public void initSkegn(final Context mContext,final OnSkEgnInitListener onSkEgnInitListener){
//        this.onSkEgnInitListener=onSkEgnInitListener;
        final EngineSetting setting = EngineSetting.getInstance(mContext);
        setting.setOnInitEngineListener(new OnInitEngineListener() {
            @Override
            public void onStartInitEngine() {
                //开始初始化引擎
                if(onSkEgnInitListener!=null)
                onSkEgnInitListener.onStartInitEngine();
            }

            @Override
            public void onInitEngineSuccess() {
                //初始化引擎成功
                Log.e("aaaaaaa","打分引擎初始化成功!");
                if(onSkEgnInitListener!=null)
                onSkEgnInitListener.onInitEngineSuccess();
            }

            @Override
            public void onInitEngineFailed() {
                //初始化引擎失败
//                isInitSkEgn=true;
                if(onSkEgnInitListener!=null)
                onSkEgnInitListener.onInitEngineFailed();
            }
        });
        new Thread(new Runnable() {
            @Override
            public void run() {
                SkEgnManager.getInstance(mContext).initCloudEngine("148757611600000f","2d5356fe1d5f3f13eba43ca48c176647","userId", setting);
            }
        }).start();
    }

    public interface OnSkEgnInitListener {

        void onStartInitEngine();//引擎开始初始化

        void onInitEngineSuccess();//引擎初始化成功

        void onInitEngineFailed();//引擎初始化失败

    }


    public interface OnLancooRecordListener{
        void onRecordStart();
        void onRecording(int vad_status, int sound_intensity);
        void onRecordEnd(int grade, String url, LgEvaluateObj skegnResult);
        void onRecordError(String error);
    }

//    @SuppressLint("HandlerLeak")
//    private Handler mHandler=new Handler(){
//        @Override
//        public void handleMessage(Message msg) {
//            super.handleMessage(msg);
//            switch (msg.what){
//                case SkEgnManager.CODE_RESULT_OK://结束打分
//                    if(isEnableScore) {
//                        isEnableScore = false;
//                        try {
//                            if (isShowScore) {
//                                String result = (String)msg.obj;
//                                final JSONObject json = new JSONObject(result);
//                                int grade = json.getJSONObject("result").getInt("overall");
//                                String path = SkEgnManager.getInstance(mContext).getPath();
//                                if (onLancooRecordListener != null && !TextUtils.isEmpty(path)) {
//                                    onLancooRecordListener.onRecordEnd(grade, path);
//                                } else {
//                                    onLancooRecordListener.onRecordError("path is empty!");
//                                }
//                            }
//                        } catch (JSONException e) {
//                            // TODO Auto-generated catch block
//                            e.printStackTrace();
//                            if (onLancooRecordListener != null && isShowScore) {
//                                onLancooRecordListener.onRecordError(e.toString());
//                            }
//                        }
//                    }
//                    break;
//            }
//        }
//    };

    private Handler mHandler=new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            if(msg.what==MST_OUTTIME){

                if(onLancooRecordListener!=null){
                    onLancooRecordListener.onRecordError("out time!");
                }
                if(mContext!=null){
                    SkEgnManager.getInstance(mContext).cancelRecord();
                    initSkegn(mContext,null);
                }
            }
            return false;
        }
    });

    public float getVolume(){
        return SkEgnManager.getInstance(mContext).getVolume();
    }
}
